<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1, '0')">添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 如果type==1(页面级别的)，才显示添加，如果type=2就没有添加按钮 -->
              <el-button v-if="scope.row.type===1" type="text" @click="hAdd(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="hedit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加权限-对话框 -->
    <el-dialog :title="edit?'编辑权限':'添加权限'" :visible.sync="showDialog" @close="hClose">
      <el-form ref="form" :model="formData" label-width="100px" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用" prop="enVisible">
          <el-switch v-model="formData.enVisible" active-text="启用" inactive-text="不启用" />
        </el-form-item>

        <el-form-item>
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { tranListToTreeData } from '@/utils/index.js'
import { getPermissionList, addPermission, delPermission, updatePermission, getPermissionDetail } from '@/api/permisson.js'
export default {
  data() {
    // 正则校验
    // var validateName = (rule, value, callback) => {
    //   // 当触发添加子部门功能时，有子部门的不能与之前子部门的名字重复，没有子部门的不用校验这一步
    //   // this.list.forEach(item => {
    //   //   if (item.children.length > 0) {
    //   //     let sameleveLlist = item.children.map(item => item.name)
    //   //     console.log('当前被占用的部门名字列表', sameleveLlist)
    //   //   }
    //   // })
    //   // .map(item => item.children)
    //   let resd = this.list.filter(item => item.children.length > 0)
    //   let resa = { ...resd }
    //   let sameleveLlist = console.log('当前被占用的部门名字列表', sameleveLlist)
    //   if (this.edit) {
    //     // 获取自身元素
    //     // 触发编辑功能时。除了被触发的部门名字，我们不能将其改成它的同级部门的名字，所以要判断是否为编辑模式下，然后把兄弟部门找出来再把自己除去，最后再去判断
    //     if (this.list.children.length > 0) {
    //       const self = this.list.find(item => item.id === this.id)
    //       sameleveLlist = this.list.filter(item => item.pid === self.pid && item.id !== this.id).map(item => item.name)
    //       console.log('同级兄弟部门名字列表', sameleveLlist)
    //     }
    //   }
    // }
    const validCode = (rule, value, callback) => {
      // 添加时的校验：code不能重复
      let existCodeList = this.originList
      if (this.edit) {
        // 编辑时的校验: code能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value) ? callback(new Error(value + '已经占用')) : callback()
    }

    const validName = (rule, value, callback) => {
      // 添加时的校验： 名字不能取子元素的名字
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      console.log('看看这是什么', existNameList, this.formData)
      if (this.edit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value) ? callback(new Error(value + '已经占用')) : callback()
    }
    return {
      formData: {
        type: '',
        pid: '',
        name: '',
        code: '',
        description: '',
        enVisible: false
      },
      edit: false,
      showDialog: false,
      originList: [],
      list: [], // 保存权限数据
      id: 1,
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '权限名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '权限编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadPermission()
  },
  methods: {
    async loadPermission() {
      const res = await getPermissionList()
      console.log('获取权限数据', res)
      // 校验要用到的数据处理
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      this.list = tranListToTreeData(res.data)
      console.log('获取list数据', this.originList)
      this.id = res.data.id
    },
    // 用户点击了添加权限
    hAdd(type, pid) {
      this.edit = false
      console.log('当前要添加的权限数据', type, pid)
      // 更新参数
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
    },
    async doAdd() {
      this.edit = false
      const res = await addPermission(this.formData)
      console.log('添加结果', res)

      this.$message.success('添加成功')
      this.showDialog = false
      this.loadPermission()
    },
    hSubmit() {
      // 表单校验
      this.$refs.form.validate(valid => {
        if (valid) {
          this.edit ? this.doedit() : this.doAdd()
        }
      })
    },
    // 删除
    async doDel(id) {
      const res = await delPermission(id)
      console.log('删除权限点', res)

      this.$message.success('删除成功')
      this.loadPermission()
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    // 用户点击了编辑
    async hedit(id) {
      this.edit = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
      this.showDialog = true
      console.log(res)
    },
    async doedit() {
      const res = await updatePermission(this.formData)
      console.log(res)
      this.showDialog = false
      this.loadPermission()
    },
    // showDialog: true  --> false
    hClose() {
      // 清空表单
      // 1. 清空数据
      this.formData = {
        type: '',
        pid: '',
        name: '',
        code: '',
        description: '',
        enVisible: false
      }
      // 2. 清空表单校验结果
      this.$refs.form.resetFields()
    }
  }
}
</script>
